<template>
    <div>
      <el-row :gutter="20">
        <!-- 左侧规则分组树 -->
        <el-col :lg="5" :xl="4" style="margin-bottom: 17px">
          <div class="rule-sidebar">
            <div class="rule-sidebar-header">
              <span>规则分组</span>
              <el-button type="text" icon="el-icon-plus" size="mini" @click="handleGroupEdit()">新建</el-button>
            </div>
            <el-input
                placeholder="输入关键字进行过滤"
                v-model="leftTreeFilterText"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin: 10px 0"
            ></el-input>
            <div class="rule-tree-container" :style="{ height: (leftTreeHeight - 100) + 'px' }">
              <el-tree
                  class="filter-tree rule-tree"
                  :data="leftTreeData"
                  :props="defaultProps"
                  default-expand-all
                  :filter-node-method="leftTreeFilterNode"
                  highlight-current
                  ref="tree"
                  @node-click="chooseLeftTree"
                  node-key="id"
              >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span @click.stop="chooseLeftTree(data)">{{ node.label }}</span>
                  <span v-if="data.id && data.id !== -1 && data.scenarioSource !== 'generate'" class="node-actions">
                    <i class="el-icon-edit" @click.stop="handleGroupEdit(data)"></i>
                    <i class="el-icon-delete" @click.stop="handleGroupDelete(data)"></i>
                  </span>
                </span>
              </el-tree>
            </div>
          </div>
        </el-col>

        <!-- 中间规则列表 -->
        <el-col :lg="10" :xl="11">
          <div class="rule-content">
            <div class="rule-content-header">
              <span class="rule-content-title">审查规则</span>
              <div class="rule-content-actions">
                <el-button
                        type="primary"
                        size="medium"
                        icon="el-icon-plus"
                        @click="handleEdit()"
                >新建规则</el-button>
                <i
                  class="el-icon-download action-icon"
                  @click="handleExport"
                ></i>
                <i
                  class="el-icon-refresh action-icon"
                  @click="refresh"
                ></i>
              </div>
            </div>

            <!-- 搜索框 -->
            <div class="rule-search">
              <el-input
                  placeholder="请输入规则名称或规则描述关键词进行搜索"
                  prefix-icon="el-icon-search"
                  v-model="queryForm.ruleName"
                  clearable
                  @keyup.enter.native="queryList({current:1})"
                  @clear="queryList({current:1})"
                  class="full-width-input"
              ></el-input>
            </div>

            <!-- 多选操作区 -->
            <div class="batch-actions" v-if="selectedItems.length > 0">
              <div class="selection-info">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
                  已选择 {{ selectedItems.length }}/{{ tableData.length }} 项
                </el-checkbox>
              </div>
              <div class="batch-buttons">
                <el-button type="danger" size="small" @click="handleDeleteBatch">批量删除</el-button>
                <el-button type="primary" size="small" @click="handleBatchChangeGroup">修改规则分组</el-button>
              </div>
            </div>

            <!-- 高级搜索 -->
            <el-form v-if="advancedSearch" :inline="true" :model="queryForm" @submit.native.prevent @keyup.enter.native="queryList" class="rule-advanced-search">
                <el-form-item>
                    <el-input prefix-icon="el-icon-search" v-model="queryForm.ruleDesc" autocomplete="off" placeholder="请输入规则描述" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="queryForm.ruleSource" placeholder="请选择规则来源" clearable>
                      <el-option label="自设" value="create"></el-option>
                      <el-option label="智能" value="generate"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="queryForm.riskLevel" placeholder="请选择风险级别" clearable>
                      <el-option label="高风险" value="high"></el-option>
                      <el-option label="中风险" value="medium"></el-option>
                      <el-option label="低风险" value="low"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="medium" icon="el-icon-search" @click="queryList({current:1})">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button size="medium" icon="el-icon-refresh-left" @click="resetQueryForm">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- loading -->
            <loading :show="parentShow">
                <el-table
                    ref="multipleTable"
                    :data="tableData"
                    style="width: 100%; margin-bottom: 20px"
                    row-key="id"
                    @row-click="handleRowClick"
                    highlight-current-row
                    class="rule-table"
                    :header-cell-style="{background:'#f5f7fa', color:'#606266', fontWeight:'500'}"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                    ></el-table-column>

                    <el-table-column width="100">
                      <template slot-scope="scope">
                        <span
                          :class="['risk-badge',
                                  scope.row.riskLevel === 'high' ? 'risk-high' :
                                  scope.row.riskLevel === 'medium' ? 'risk-medium' : 'risk-low']"
                        >
                          {{ getRiskLevelText(scope.row.riskLevel) }}
                        </span>
                      </template>
                    </el-table-column>

                    <el-table-column prop="ruleName" label="规则名称" min-width="180">
                      <template slot-scope="scope">
                        <div class="rule-name-cell">
                          <div class="rule-name">{{ scope.row.ruleName }}</div>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column prop="ruleSource" label="规则来源" width="100" align="center">
                      <template slot-scope="scope">
                        <div class="source-tag source-generate" v-if="scope.row.ruleSource === 'generate'">
                          智能
                        </div>
                        <div class="source-tag source-create" v-else>
                          {{ scope.row.ruleSource === 'create' ? '自设' : scope.row.ruleSource }}
                        </div>
                      </template>
                    </el-table-column>
                </el-table>
            </loading>
            <pagination :total="page.total" :current-page="page.current" :page-size="page.size" @refreshData="queryList"></pagination>
            <!-- 新增、编辑 -->
            <form-edit
                    v-if="formEditVisible"
                    ref="formEdit"
                    :leftTreeData="leftTreesimple"
                    @refreshData="queryList"
            ></form-edit>
            <!-- 详情 -->
            <form-info v-if="formInfoVisible" ref="formInfo"></form-info>
          </div>
        </el-col>

        <!-- 右侧规则详情 -->
        <el-col :lg="9" :xl="9">
          <div class="rule-detail-panel" v-if="currentRule">
            <div class="rule-detail-header">
              <span class="rule-detail-title">规则详情</span>
              <div class="rule-detail-actions">
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-edit"
                  @click="handleEdit(currentRule)"
                  v-if="currentRule && currentRule.ruleSource !== 'generate'"
                  :disabled="selectedItems.length >= 1"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  @click="handleDelete(currentRule)"
                  v-if="currentRule && currentRule.ruleSource !== 'generate'"
                  :disabled="selectedItems.length >= 1"
                >删除</el-button>
                <el-tooltip
                  content="智能生成的规则不允许编辑或删除"
                  placement="top"
                  v-if="currentRule && currentRule.ruleSource === 'generate'"
                >
                  <span class="generate-rule-tip"><i class="el-icon-info"></i> 智能生成规则</span>
                </el-tooltip>
                <el-tooltip
                  content="多选状态下请使用批量操作"
                  placement="top"
                  v-if="selectedItems.length >= 1"
                >
                  <span class="multi-select-tip"><i class="el-icon-info"></i> 多选状态</span>
                </el-tooltip>
              </div>
            </div>

            <div class="detail-item">
              <div class="detail-label">规则名称</div>
              <div class="detail-text">{{ currentRule.ruleName }}</div>
            </div>

            <div class="detail-item">
              <div class="detail-label">风险等级</div>
              <div class="risk-level-tag">
                <span
                  :class="['risk-badge',
                          currentRule.riskLevel === 'high' ? 'risk-high' :
                          currentRule.riskLevel === 'medium' ? 'risk-medium' : 'risk-low']"
                >
                  {{ getRiskLevelText(currentRule.riskLevel) }}
                </span>
              </div>
            </div>

            <div class="detail-item">
              <div class="detail-label">规则描述</div>
              <div class="detail-text">{{ currentRule.ruleDesc }}</div>
            </div>

            <div class="detail-item" v-if="currentRule.message">
              <div class="detail-label">消息内容</div>
              <div class="detail-text">{{ currentRule.message }}</div>
            </div>
          </div>

          <div class="rule-detail-empty" v-else>
            <div class="empty-placeholder">
              <i class="el-icon-document"></i>
              <p>请选择一条规则查看详情</p>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 规则分组新建/编辑弹窗 -->
      <rule-group-edit v-if="groupEditVisible" ref="ruleGroupEdit" @refreshData="queryLeftTreeList"></rule-group-edit>

      <!-- 修改规则分组弹窗 -->
      <el-dialog
          title="修改规则分组"
          :visible.sync="groupEditDialogVisible"
          width="500px"
          :close-on-click-modal="false"
          @closed="targetGroupId = ''"
      >
          <div class="group-edit-form">
              <div class="form-item">
                  <label class="required-label">规则分组名称：</label>
                  <el-select
                      v-model="targetGroupId"
                      filterable
                      placeholder="请选择规则分组"
                      style="width: 100%"
                  >
                      <el-option
                          v-for="group in groupOptions"
                          :key="group.id"
                          :label="group.title"
                          :value="group.id"
                      >
                      </el-option>
                  </el-select>
              </div>

              <!-- 新增创建规则分组功能 -->
              <div class="create-group-box">
                  <el-input
                      v-model="newGroupName"
                      placeholder="请输入新的规则..."
                      maxlength="30"
                      show-word-limit
                      size="small"
                  ></el-input>
                  <el-button
                      type="text"
                      size="small"
                      icon="el-icon-plus"
                      @click="createNewGroup"
                  >创建为规则分组</el-button>
              </div>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button @click="groupEditDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmUpdateGroup">确定</el-button>
          </span>
      </el-dialog>
    </div>
</template>
<script>
    import { rulePage, ruleDel, ruleDelBatch, ruleDynamicExport, leftTreeList, ruleInfo, ruleGroupDelete, updateRuleGroup, ruleGroupSave } from "@/api/rule/rule/rule.js";
    import { viewTableList } from "@/api/public.api.js";
    import FormEdit from "./rule-edit";
    import FormInfo from "./rule-info";
    import RuleGroupEdit from "./rule-group-edit";
    import FortressPagination from "@/components/fortress-pagination.vue";

    export default {
        data() {
            return {
                leftTreeHeight: 0,
                leftTreeFilterText:"",
                parentShow: false,
                tableData: [],
                leftTreeData: [],
                leftTreesimple: [],
                defaultProps: {
                  children: "children",
                  label: "title",
                },
                sleLeftTreeId:"",
                sleLeftTreeName:"",
                formEditVisible: false,
                formInfoVisible: false,
                selectedItems: [],
                batchSelectedRules: [],
                checkAll: false,
                isIndeterminate: false,
                queryForm: {
                        id:"",
                        ruleName:"",
                        ruleDesc:"",
                        ruleType:"",
                        ruleSource:"",
                        riskLevel:"",
                        updateTime:"",
                        message:"",
                        scenarioId:"",
                        createUser:"",
                        createTime:"",
                        updateUser:"",
                        isDeleted:"",
                },
                page: {
                    current: 1,
                    size: 10,
                    total: 0,
                },
                collapse: {
                    icon: "el-icon-arrow-down el-icon--right",
                    label: "展开",
                    flag: false,
                },
                tableList: [],
                tableShowList: [],
                advancedSearch: false,
                currentRule: null,
                groupEditVisible: false,
                groupEditDialogVisible: false,
                targetGroupId: '',
                groupOptions: [],
                newGroupName: '',
            };
        },
        components: {
            "form-edit": FormEdit,
            "form-info": FormInfo,
            "rule-group-edit": RuleGroupEdit,
            pagination: FortressPagination,
        },
        created() {
            this.leftTreeHeight = window.innerHeight * 0.8;
            this.queryLeftTreeList();
            this.initTableList();
            this.queryList();
        },
        mounted() {
            // 页面完全挂载后再次尝试选中第一个节点
            setTimeout(() => {
                try {
                    if (this.leftTreeData && this.leftTreeData.length > 0 && this.$refs.tree) {
                        let firstNode = this.leftTreeData[0];
                        if (firstNode.children && firstNode.children.length > 0) {
                            firstNode = firstNode.children[0];
                        }
                        console.log("mounted中尝试选中节点:", firstNode);
                        this.$refs.tree.setCurrentKey(firstNode.id);
                        this.$refs.tree.setCurrentNode(firstNode);
                        this.chooseLeftTree(firstNode);
                    }
                } catch (error) {
                    console.error("mounted中设置选中失败:", error);
                }
            }, 1000);
        },
        watch: {
          leftTreeFilterText(val) {
            this.$refs.tree.filter(val);
           },
        },
        methods: {
            //查询左树数据
            queryLeftTreeList() {
              this.leftTreeData = [];
              leftTreeList().then((resp) => {
                if (resp.code == 0) {
                  this.leftTreesimple = resp.data;
                  this.leftTreeData = resp.data;

                  // 左侧树加载完成后，默认选中第一个节点（如果有）
                  this.$nextTick(() => {
                    try {
                      if (this.leftTreeData && this.leftTreeData.length > 0) {
                        // 获取第一个节点，如果第一个项目有子节点，则选第一个子节点
                        let firstNode = this.leftTreeData[0];
                        console.log("准备选中节点:", firstNode);

                        if (firstNode.children && firstNode.children.length > 0) {
                          // 如果有子节点，选择第一个子节点
                          firstNode = firstNode.children[0];
                          console.log("选择子节点:", firstNode);
                        }

                        // 确保节点具有id属性
                        if (firstNode && firstNode.id) {
                          console.log("最终选中节点ID:", firstNode.id);
                          // 尝试多种方法设置选中状态
                          if (this.$refs.tree) {
                            this.$refs.tree.setCurrentKey(firstNode.id);
                            this.$refs.tree.setCurrentNode(firstNode);
                            // 手动触发节点点击事件
                            this.chooseLeftTree(firstNode);
                          } else {
                            console.error("树引用不存在");
                            // 如果引用不存在，延迟再次尝试
                            setTimeout(() => {
                              if (this.$refs.tree) {
                                this.$refs.tree.setCurrentKey(firstNode.id);
                                this.$refs.tree.setCurrentNode(firstNode);
                                this.chooseLeftTree(firstNode);
                              }
                            }, 500);
                          }
                        } else {
                          console.error("节点缺少ID属性:", firstNode);
                        }
                      } else {
                        console.log("左侧树数据为空");
                      }
                    } catch (error) {
                      console.error("设置默认选中节点失败:", error);
                    }
                  });
                } else {
                  this.$msg({
                    message: resp.msg,
                    type: "error",
                  });
                }
              });
            },
            leftTreeFilterNode(value, data) {
              if (!value) return true;
              return data.title.indexOf(value) !== -1;
            },
            //点选左侧树
            chooseLeftTree(data) {
              if (data.id == -1) {
                this.sleLeftTreeId = "";
                this.sleLeftTreeName = "";
                this.queryRightTable("");
              } else {
                this.sleLeftTreeId = data.id;
                this.sleLeftTreeName = data.title;
                this.queryRightTable(data.id);
              }
              // 清除当前选中的规则
              this.currentRule = null;
            },
            //点击左树筛选右侧表格数据
            queryRightTable(sleLeftTreeId) {
              this.queryForm.scenarioId = sleLeftTreeId;
              this.queryList();
            },
            refresh() {
              this.tableData = [];
              this.queryList({ current: 1 });
              // 清除当前选中的规则
              this.currentRule = null;
            },
            //查询表格数据
            queryList(page) {
                this.parentShow = true;
                if (page) {
                    this.page.current = page.current?page.current:this.page.current;
                    this.page.size = page.size?page.size:this.page.size;
                }
                // 确保每次查询都使用左侧树选中的ID
                // 如果sleLeftTreeId为空或undefined，则传递null或指定默认值
                this.queryForm.scenarioId = this.sleLeftTreeId || null;

                this.queryForm.current = this.page.current;
                this.queryForm.size = this.page.size;

                rulePage(this.queryForm).then((resp) => {
                    if (resp.code == 0) {
                        this.tableData = resp.data.records;
                        this.page.total = resp.data.total;
                        //查询页大于总页数，重新查询
                        let cu = this.page.total%this.page.size==0?parseInt(this.page.total/this.page.size):parseInt((this.page.total/this.page.size)+1);
                        if(cu>0 && this.page.current>cu){
                          this.queryList({current:cu});
                        }
                        // 清除当前选中的规则
                        this.currentRule = null;

                        // 如果列表不为空，默认加载第一条记录的详情
                        if (this.tableData && this.tableData.length > 0) {
                            this.$nextTick(() => {
                                this.getRowDetail(this.tableData[0].id);
                                // 高亮第一行
                                this.$refs.multipleTable.setCurrentRow(this.tableData[0]);
                            });
                        }
                    } else {
                        this.$msg({
                            message: resp.msg,
                            type: "error",
                        });
                    }
                    this.parentShow = false;
                });
            },
            //打开编辑窗口
            handleEdit(row){
                // 如果是智能生成的规则，不允许编辑
                if(row && row.ruleSource === 'generate') {
                    this.$msg({
                        message: "智能生成的规则不允许编辑",
                        type: "warning",
                    });
                    return;
                }

                //新增
                if(!row){
                    if(!this.sleLeftTreeId){
                      this.$msg({
                        message: "请选择左侧架构",
                        type: "error",
                      });
                      return;
                    }
                }
                this.formEditVisible = true;
                this.$nextTick(() => {
                    if(row){
                        this.$refs.formEdit.init(row.id);
                    }else{
                        this.$refs.formEdit.init(undefined,this.sleLeftTreeId,this.sleLeftTreeName);
                    }
                });
            },

            // 点击表格行获取详情
            handleRowClick(row) {
                this.getRowDetail(row.id);
            },

            // 获取行详情
            getRowDetail(id) {
                ruleInfo(id).then((resp) => {
                    if (resp.code == 0) {
                        this.currentRule = resp.data;
                    } else {
                        this.$msg({
                            message: resp.msg,
                            type: "error",
                        });
                    }
                });
            },

            //打开详情窗口 (保留原方法用于兼容性)
            handleInfo(id) {
                this.getRowDetail(id);
            },

            //删除
            handleDelete(row) {
                // 如果是智能生成的规则，不允许删除
                if(row && row.ruleSource === 'generate') {
                    this.$msg({
                        message: "智能生成的规则不允许删除",
                        type: "warning",
                    });
                    return;
                }

                this.$confirm('确认删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                        ruleDel(row.id).then((resp) => {
                        if (resp.code == 0) {
                            this.$message({
                                type: "success",
                                message: "操作成功!",
                            });
                           //判断是否最后一页的最后一条记录
                           let totalPages =
                              (this.page.total - 1) % this.page.size == 0
                                  ? (this.page.total - 1) / this.page.size
                                  : (this.page.total - 1) / this.page.size + 1;
                           if (this.page.current > totalPages && this.page.current != 1) {
                            this.page.current = this.page.current - 1;
                           }
                            this.queryList();
                            // 清除当前选中的规则
                            this.currentRule = null;
                        } else {
                            this.$msg({
                                message: resp.msg,
                                type: "error",
                            });
                        }
                    });
                }).catch(() => {
                });
            },
            //批量删除
            handleDeleteBatch() {
                let checkedRow = this.selectedItems;
                if (checkedRow.length > 0) {
                    // 检查是否包含智能生成的规则
                    const hasGenerateRule = checkedRow.some(item => item.ruleSource === 'generate');
                    if (hasGenerateRule) {
                        this.$msg({
                            message: "智能生成的规则不允许删除，请取消选择这些规则",
                            type: "warning",
                        });
                        return;
                    }

                    let ids = [];
                    checkedRow.forEach((item) => {
                        ids.push(item.id);
                    });
                    this.$confirm("确认删除所选记录, 是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    })
                            .then(() => {
                                ruleDelBatch(ids).then((resp) => {
                                    if (resp.code == 0) {
                                        this.$message({
                                            type: "success",
                                            message: "操作成功!",
                                        });
                                      //判断是否最后一页的最后一条记录
                                      let totalPages =
                                          (this.page.total - checkedRow.length) % this.page.size == 0
                                              ? (this.page.total - checkedRow.length) / this.page.size
                                              : (this.page.total - checkedRow.length) / this.page.size +
                                              1;
                                      if (this.page.current > totalPages && this.page.current != 1) {
                                        this.page.current = this.page.current - 1;
                                      }
                                        this.queryList();
                                        // 清除选择
                                        this.selectedItems = [];
                                    } else {
                                        this.$msg({
                                            message: resp.msg,
                                            type: "error",
                                        });
                                    }
                                });
                            })
                            .catch(() => {});
                } else {
                    this.$msg({
                        message: "请选择数据进行删除",
                        type: "error",
                    });
                }
            },
            //重置查询框
            resetQueryForm() {
                this.queryForm = {
                        id:"",
                        ruleName:"",
                        ruleDesc:"",
                        ruleType:"",
                        ruleSource:"",
                        riskLevel:"",
                        updateTime:"",
                        message:"",
                        scenarioId: this.sleLeftTreeId,
                        createUser:"",
                        createTime:"",
                        updateUser:"",
                        isDeleted:"",
                };
            },
            //切换查询条件收缩框
            handleCollapseState() {
                this.collapse.flag = !this.collapse.flag;
                if (this.collapse.flag) {
                    this.collapse.icon = "el-icon-arrow-up el-icon--right";
                    this.collapse.label = "收起";
                } else {
                    this.collapse.icon = "el-icon-arrow-down el-icon--right";
                    this.collapse.label = "展开";
                }
            },
            //视图表格列表初始化
            initTableList() {
                viewTableList("rule").then((resp) => {
                    if (resp.code == 0) {
                        this.tableList = resp.data;
                        this.tableList.forEach((item) => {
                            this.tableShowList.push(item.propName);
                        });
                    }
                });
            },
            //可见字段excel导出
            handleExport() {
              if (!this.tableShowList || this.tableShowList.length < 1) {
                this.$msg({
                  message: "请选择要导出的列",
                  type: "error",
                });
                return;
              }
              let colNum = 1;
              let headerList = [];
              this.tableShowList.forEach((item) => {
                let nameData = this.tableList.find((item2) => {
                  return item2.propName == item;
                });
                let name = "";
                if (nameData && nameData.propDesc) {
                  name = nameData.propDesc;
                } else {
                  name = "未定义字段" + colNum++;
                }
                headerList.push({ name: name, code: item });
              });
            ruleDynamicExport({ headerList: headerList, dto: this.queryForm });
            },
            showAdvancedSearch() {
                this.advancedSearch = !this.advancedSearch;
            },

            //获取风险级别对应的标签类型
            getRiskLevelType(level) {
                if (level === 'high') return 'danger';
                if (level === 'medium') return 'warning';
                if (level === 'low') return 'info';
                return 'warning';
            },

            //获取风险级别对应的中文文本
            getRiskLevelText(level) {
                if (level === 'high') return '高风险';
                if (level === 'medium') return '中风险';
                if (level === 'low') return '低风险';
                return '中风险';
            },

            handleGroupEdit(data) {
                // 检查是否为智能生成的规则分组，阻止编辑
                if (data && data.scenarioSource === 'generate') {
                    this.$msg({
                        message: "智能生成的规则分组不允许修改",
                        type: "warning",
                    });
                    return;
                }

                this.groupEditVisible = true;
                this.$nextTick(() => {
                    this.$refs.ruleGroupEdit.init(data);
                });
            },
            handleGroupDelete(data) {
                // 检查是否为智能生成的规则分组，阻止删除
                if (data && data.scenarioSource === 'generate') {
                    this.$msg({
                        message: "智能生成的规则分组不允许删除",
                        type: "warning",
                    });
                    return;
                }

                this.$confirm('确认删除当前规则分组？删除规则分组将同时删除该场景下的所有审查规则，该操作不可撤回，请谨慎操作。', '提示', {
                    confirmButtonText: '删除规则分组及规则',
                    cancelButtonText: '取消',
                    type: 'warning',
                    customClass: 'delete-confirm-dialog'
                }).then(() => {
                    // 实现删除规则组的逻辑
                    console.log('删除规则组ID:', data.id, typeof data.id);
                    ruleGroupDelete(data.id).then(resp => {
                        if (resp.code == 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                            this.queryLeftTreeList();
                        } else {
                            this.$msg({
                                message: resp.msg,
                                type: "error",
                            });
                        }
                    }).catch(error => {
                        console.error('删除规则组出错:', error);
                        this.$msg({
                            message: '删除失败，请检查网络或联系管理员',
                            type: "error",
                        });
                    });
                }).catch(() => {});
            },
            handleSelectionChange(selection) {
                this.selectedItems = selection;
                this.checkAll = selection.length === this.tableData.length;
                this.isIndeterminate = selection.length > 0 && selection.length < this.tableData.length;
                console.log("选择变更，当前选中项:", selection);
            },
            handleCheckAllChange(val) {
                this.$refs.multipleTable.clearSelection();
                if (val) {
                    this.tableData.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row, true);
                    });
                }
                this.isIndeterminate = false;
            },
            handleBatchChangeGroup() {
                if (this.selectedItems.length === 0) {
                    this.$msg({
                        message: "请至少选择一条规则",
                        type: "warning"
                    });
                    return;
                }

                // 判断是否包含智能生成的规则
                const hasGenerateRule = this.selectedItems.some(item => item.ruleSource === 'generate');
                if (hasGenerateRule) {
                    this.$msg({
                        message: "智能生成的规则不允许修改分组，请取消选择这些规则",
                        type: "warning"
                    });
                    return;
                }

                // 在全局变量中保存当前选中的规则
                this.batchSelectedRules = [...this.selectedItems];
                console.log("打开修改分组弹窗，保存选中规则:", this.batchSelectedRules);

                // 显示选择分组弹窗
                this.showSelectGroupDialog();
            },

            // 显示选择分组弹窗
            showSelectGroupDialog() {
                // 准备分组选项，排除全部节点和智能生成的分组
                this.groupOptions = [];
                this.leftTreesimple.forEach(item => {
                    if (item.id !== -1) {
                        this.groupOptions.push({
                            id: item.id,
                            title: item.title
                        });
                    }
                });

                // 显示弹窗
                this.groupEditDialogVisible = true;
            },

            // 确认更新规则分组
            confirmUpdateGroup() {
                if (!this.targetGroupId) {
                    this.$msg({
                        message: "请选择目标分组",
                        type: "warning"
                    });
                    return;
                }

                // 使用保存的规则列表，而不是当前的selectedItems
                const ruleIds = this.batchSelectedRules.map(item => item.id);

                // 添加日志，检查IDs是否正确
                console.log("准备更新规则分组，规则IDs:", ruleIds, "目标分组ID:", this.targetGroupId);

                // 验证规则ID列表是否为空
                if (!ruleIds || ruleIds.length === 0) {
                    this.$msg({
                        message: "未选择任何规则或选择已失效，请重新选择规则",
                        type: "warning"
                    });
                    // 关闭弹窗
                    this.groupEditDialogVisible = false;
                    return;
                }

                // 调用API更新规则分组
                updateRuleGroup(ruleIds, this.targetGroupId).then(resp => {
                    if (resp.code == 0) {
                        this.$message({
                            type: "success",
                            message: resp.data || "修改规则分组成功！"
                        });
                        // 关闭弹窗
                        this.groupEditDialogVisible = false;
                        // 刷新列表
                        this.queryList();
                        // 清除选择
                        this.$refs.multipleTable.clearSelection();
                        this.selectedItems = [];
                        this.batchSelectedRules = [];
                    } else {
                        this.$msg({
                            message: resp.msg || "修改规则分组失败",
                            type: "error"
                        });
                    }
                }).catch(error => {
                    console.error("修改规则分组出错:", error);
                    this.$msg({
                        message: "修改规则分组失败，请检查网络或联系管理员",
                        type: "error"
                    });
                });
            },

            // 创建新的规则分组
            createNewGroup() {
                if (!this.newGroupName || this.newGroupName.trim() === '') {
                    this.$msg({
                        message: "请输入规则分组名称",
                        type: "warning"
                    });
                    return;
                }

                // 构建保存数据
                const saveData = {
                    title: this.newGroupName.trim(),
                    scenarioSource: 'create'
                };

                // 保存原始选中项，防止创建过程中丢失
                const originalSelectedItems = [...this.selectedItems];

                // 调用API创建新规则分组
                ruleGroupSave(saveData).then(resp => {
                    if (resp.code == 0) {
                        this.$message({
                            type: "success",
                            message: "创建规则分组成功！"
                        });

                        // 确保selectedItems不丢失
                        if (originalSelectedItems.length > 0) {
                            this.selectedItems = originalSelectedItems;
                        }

                        // 刷新左侧树数据
                        this.queryLeftTreeList();

                        // 清空输入框
                        this.newGroupName = '';

                        // 记录创建前选中状态
                        console.log("创建新分组前选中项:", this.selectedItems);

                        // 重新获取分组选项
                        setTimeout(() => {
                            // 更新分组选项，并将新创建的分组设为选中状态
                            this.groupOptions = [];
                            this.leftTreesimple.forEach(item => {
                                if (item.id !== -1) {
                                    this.groupOptions.push({
                                        id: item.id,
                                        title: item.title
                                    });

                                    // 如果名称匹配，则选中该项
                                    if (item.title === saveData.title) {
                                        this.targetGroupId = item.id;
                                    }
                                }
                            });

                            // 记录创建后选中状态
                            console.log("创建新分组后选中项:", this.selectedItems, "目标分组ID:", this.targetGroupId);
                        }, 500);
                    } else {
                        this.$msg({
                            message: resp.msg || "创建规则分组失败",
                            type: "error"
                        });
                    }
                }).catch(error => {
                    console.error("创建规则分组出错:", error);
                    this.$msg({
                        message: "创建规则分组失败，请检查网络或联系管理员",
                        type: "error"
                    });
                });
            },
        },
    };
</script>
<style scoped>
  .padding10 {
    padding: 10px 20px;
    background-color: #fff;
    overflow: auto;
    border-radius: 4px;
    box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  }
  .tree {
    height: 600px;
    overflow: auto;
  }
  .rule-sidebar {
    background-color: #fff;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
  }
  .rule-sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
  }
  .rule-sidebar-header span {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
  .rule-sidebar-header .el-button {
    padding: 6px 10px;
    font-size: 13px;
  }
  .rule-sidebar .el-input {
    margin-bottom: 15px;
  }
  .rule-sidebar .el-input .el-input__inner {
    border-radius: 20px;
    height: 36px;
    background-color: #f5f7fa;
    border-color: #f5f7fa;
    transition: all 0.3s;
  }
  .rule-sidebar .el-input .el-input__inner:hover,
  .rule-sidebar .el-input .el-input__inner:focus {
    background-color: #fff;
    border-color: #409EFF;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
  .rule-tree-container {
    overflow: auto;
    flex: 1;
    padding: 5px;
    scrollbar-width: thin;
  }
  .rule-tree-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  .rule-tree-container::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }
  .rule-tree-container::-webkit-scrollbar-track {
    background: #f5f7fa;
  }
  .rule-tree .el-tree-node__content {
    height: 40px;
    padding: 8px 0;
    margin: 3px 0;
    border-radius: 4px;
    transition: all 0.2s;
  }
  .rule-tree .el-tree-node__content:hover {
    background-color: #f0f7ff;
  }
  .rule-tree .el-tree-node.is-current > .el-tree-node__content {
    background-color: #ecf5ff;
    color: #409EFF;
    font-weight: 500;
  }
  .rule-tree .el-tree-node__label {
    font-size: 14px;
    color: #606266;
  }
  .rule-tree .el-tree-node.is-current .el-tree-node__label {
    color: #409EFF;
  }
  .rule-tree .el-tree-node__expand-icon {
    color: #909399;
    font-size: 14px;
  }
  .rule-tree .el-tree-node__expand-icon.expanded {
    color: #409EFF;
  }
  .custom-tree-node {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    padding: 0 5px;
  }
  .node-actions {
    visibility: hidden;
    transition: all 0.2s;
  }
  .custom-tree-node:hover .node-actions {
    visibility: visible;
  }
  .node-actions i {
    margin-left: 8px;
    font-size: 16px;
    color: #909399;
    cursor: pointer;
    transition: all 0.2s;
  }
  .node-actions i:hover {
    transform: scale(1.2);
  }
  .node-actions i.el-icon-edit:hover {
    color: #409EFF;
  }
  .node-actions i.el-icon-delete {
    color: #F56C6C;
  }
  .node-actions i.el-icon-delete:hover {
    color: #FF4949;
  }
  .rule-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    height: calc(100vh - 40px);
    overflow: auto;
  }
  .rule-content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }
  .rule-content-title {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
  }
  .rule-content-actions {
    display: flex;
    align-items: center;
  }
  .action-icon {
    margin-left: 15px;
    font-size: 20px;
    color: #409EFF;
    cursor: pointer;
    transition: all 0.2s;
  }
  .action-icon:hover {
    transform: scale(1.2);
    color: #66b1ff;
  }
  .rule-search {
    display: flex;
    margin-bottom: 20px;
  }
  .rule-search .el-input {
    margin-right: 10px;
  }
  .rule-advanced-search {
    margin-top: 10px;
  }
  .rule-detail-panel {
    background-color: #fff;
    padding: 24px;
    border-radius: 4px;
    box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
    height: calc(100vh - 40px);
    overflow: auto;
    position: relative;
  }
  .rule-detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }
  .rule-detail-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
  .rule-detail-actions {
    display: flex;
    gap: 10px;
    align-items: center;
  }
  .setting-icon {
    font-size: 18px;
    color: #409EFF;
    cursor: pointer;
    margin-left: 10px;
  }
  .rule-name {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 20px;
    color: #303133;
    line-height: 1.4;
  }
  .detail-item {
    margin-bottom: 20px;
  }
  .detail-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 8px;
  }
  .detail-text {
    color: #303133;
    line-height: 1.6;
    font-size: 14px;
    background-color: #f5f7fa;
    padding: 12px 16px;
    border-radius: 4px;
    white-space: pre-line;
  }
  .risk-level-tag {
    margin-bottom: 8px;
  }
  .rule-detail-empty {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
    height: calc(100vh - 40px);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .empty-placeholder {
    text-align: center;
    color: #909399;
  }
  .empty-placeholder i {
    font-size: 48px;
    margin-bottom: 10px;
  }
  .generate-rule-tip {
    font-size: 12px;
    color: #909399;
    display: inline-flex;
    align-items: center;
    background: #f5f7fa;
    padding: 5px 10px;
    border-radius: 4px;
  }
  .generate-rule-tip i {
    margin-right: 5px;
    color: #E6A23C;
  }

  .multi-select-tip {
    font-size: 12px;
    color: #909399;
    display: inline-flex;
    align-items: center;
    background: #f5f7fa;
    padding: 5px 10px;
    border-radius: 4px;
  }
  .multi-select-tip i {
    margin-right: 5px;
    color: #409EFF;
  }
  .rule-table {
    border-radius: 6px;
    overflow: hidden;
    border: 1px solid #ebeef5;
  }
  .rule-table.el-table {
    margin-bottom: 20px;
  }
  .rule-table .el-table__row {
    cursor: pointer;
    transition: all 0.2s;
  }
  .rule-table .el-table__row:hover {
    background-color: #f0f7ff !important;
  }
  .rule-table .el-table__row.current-row {
    background-color: #ecf5ff !important;
  }
  .rule-name-cell {
    padding: 8px 0;
  }
  .rule-name {
    font-weight: 500;
    color: #303133;
    margin-bottom: 5px;
    font-size: 14px;
  }
  .rule-desc {
    color: #909399;
    font-size: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .risk-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 16px;
    font-size: 12px;
    color: white;
    text-align: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  .risk-high {
    background-color: #F56C6C;
  }
  .risk-medium {
    background-color: #E6A23C;
  }
  .risk-low {
    background-color: #909399;
  }
  .source-tag {
    padding: 4px 12px;
    border-radius: 16px;
    font-size: 12px;
    color: white;
    text-align: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  .source-generate {
    background-color: #409EFF;
  }
  .source-create {
    background-color: #67C23A;
  }

  .full-width-input {
    width: 100%;
  }

  .batch-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f0f9ff;
    padding: 10px 15px;
    border-radius: 4px;
    margin-bottom: 15px;
  }

  .selection-info {
    display: flex;
    align-items: center;
  }

  .batch-buttons {
    display: flex;
    gap: 10px;
  }

  /* 添加修改规则分组弹窗相关样式 */
  .group-edit-form {
    padding: 20px;
  }
  .form-item {
    margin-bottom: 20px;
  }
  .required-label::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
  }

  .create-group-box {
    margin-top: 15px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .create-group-box .el-input {
    width: 100%;
    margin-bottom: 10px;
  }

  .create-group-box .el-button {
    color: #409EFF;
  }
</style>

